package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import one.stand.code.RedisCode;
import one.stand.entity.WxNoticeEntity;
import one.stand.enums.LoginEnum;
import one.stand.enums.SeeRecordEnums;
import one.stand.enums.WxNoticeEnums;
import one.stand.model.*;
import one.stand.request.*;
import one.stand.response.*;
import one.stand.service.BaseService;
import one.stand.service.PersonalService;
import one.stand.service.WxMessageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author Administrator
 */
@Service
public class PersonalServiceImpl extends BaseService implements PersonalService {

    @Override
    public ResultModel addCollection(CollectionRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        CollectionModel collectionModel = new CollectionModel();
        BeanUtils.copyProperties(request, collectionModel);
        collectionModel.setUserId(request.getId().intValue());
        collectionModel.setCreateTime(currentDate());
        r = collectionMapper.insertSelective(collectionModel);
        if (r > 0) {
            return ResultModel.success("保存成功");
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel delCollection(CollectionRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        CollectionModel model = new CollectionModel();
        BeanUtils.copyProperties(request, model);
        model.setUserId(request.getId().intValue());
        r = collectionMapper.delCollection(model);
        if (r > 0) {
            return ResultModel.success("删除成功");
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel getCollection(CollectionRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        CollectionModel collectionModel = new CollectionModel();
        collectionModel.setUserId(request.getId().intValue());
        collectionModel.setItemType(request.getItemType());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CollectionModel> list = collectionMapper.select(collectionModel);
        if (list == null) {
            return ResultModel.noData();
        }
        List<CollectionResponse> responseList = new ArrayList<>();
        list.forEach(cl -> {
            CollectionResponse collectionResponse = new CollectionResponse();
            BeanUtils.copyProperties(cl, collectionResponse);
            responseList.add(collectionResponse);
        });
        PageInfo<CollectionResponse> pageInfo = new PageInfo<>(responseList);
        return ResultModel.success(pageInfo.getList());
    }

    @Override
    public ResultModel<Integer> getIsCollection(CollectionRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        CollectionModel model = new CollectionModel();
        BeanUtils.copyProperties(request, model);
        model.setUserId(request.getId().intValue());
        return ResultModel.success(collectionMapper.isCollection(model));
    }

    @Override
    public ResultModel addAddress(AddressRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        if(StringUtils.isBlank(request.getDetailedAddress()) || StringUtils.isBlank(request.getLocationAddress())){
            return ResultModel.fail("请输入完整地址哦 亲~!");
        }
        AddressModel addressModel = new AddressModel();
        BeanUtils.copyProperties(request, addressModel);
        addressModel.setUserId(request.getId().intValue());
        List<AddressModel> list = addressMapper.selectDefault(request.getId().intValue());
        if (list == null || list.size() <= 0) {
            addressModel.setIsdefault(1);
        } else {
            addressModel.setIsdefault(0);
        }
        addressModel.setCreateTime(new Date());
        r = addressMapper.insertSelective(addressModel);
        if (r > 0) {
            return ResultModel.success("保存成功");
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel updAddress(AddressRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        if(StringUtils.isBlank(request.getDetailedAddress()) || StringUtils.isBlank(request.getLocationAddress())){
            return ResultModel.fail("还是要输入完成的地址哦 亲~!");
        }
        AddressModel addressModel = new AddressModel();
        BeanUtils.copyProperties(request, addressModel);
        r = addressMapper.updateByPrimaryKeySelective(addressModel);
        if (r > 0) {
            return ResultModel.success("修改成功");
        }
        return ResultModel.fail("修改失败");
    }

    @Override
    public ResultModel delAddress(AddressRequest request) {
        if (request == null || StringUtils.isBlank(request.getAddressIds())) {
            return ResultModel.checkParamFail();
        }
        r = addressMapper.deleteAddress(request.getAddressIds().split(","));
        if (r > 0) {
            return ResultModel.success("删除成功");
        }
        return ResultModel.fail();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel isdefult(AddressRequest request) {
        if (request == null || request.getAddressId() == null) {
            return ResultModel.checkParamFail();
        }
        AddressModel addressModel = new AddressModel();
        addressModel.setIsdefault(0);
        addressModel.setUserId(request.getId().intValue());
        r = addressMapper.updateIsdefault(addressModel);
        if (r > 0) {
            addressModel = new AddressModel();
            addressModel.setIsdefault(1);
            addressModel.setAddressId(request.getAddressId());
            r = addressMapper.updateIsdefault(addressModel);
            if (r > 0) {
                return ResultModel.success("绑定成功");
            }
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel getAddress(TokenRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        AddressModel addressModel = new AddressModel();
        addressModel.setUserId(request.getId().intValue());
        List<AddressModel> list = addressMapper.select(addressModel);
        if (list == null) {
            return ResultModel.noData();
        }
        List<AddressResponse> responseList = new ArrayList<>();
        list.forEach(cl -> {
            AddressResponse addressResponse = new AddressResponse();
            BeanUtils.copyProperties(cl, addressResponse);
            responseList.add(addressResponse);
        });
        return ResultModel.success(responseList);
    }

    @Override
    public ResultModel getCompanyAllInfo(CompanyRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        CompanyModel companyModel = new CompanyModel();
        BeanUtils.copyProperties(request, companyModel);
        List<CompanyModel> list = companyMapper.selectAll(companyModel);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        List<CompanyResponse> responseList = new ArrayList<>();
        list.forEach(cl -> {
            CompanyResponse companyResponse = new CompanyResponse();
            BeanUtils.copyProperties(cl, companyResponse);
            responseList.add(companyResponse);
        });
        return ResultModel.success(responseList);
    }

    @Override
    /**@Cacheable(value = RedisCode.REDIS_DB_CACHE,key = "#root.targetClass.toString()+'.'+#root.methodName+':'+#request.toString()+':'+#request.pageSize+':'+#request.pageNum")*/
    public ResultModel<List<DynamicResponse>> getDynamicInfo(DynamicRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        DynamicModel dynamicModel = new DynamicModel();
        BeanUtils.copyProperties(request, dynamicModel);
        if (request.getCompanyId() == null) {
            dynamicModel.setCompanyId(request.getCId().intValue());
        } else {
            dynamicModel.setCompanyId(request.getCompanyId());
        }
        dynamicModel.setUserId(request.getId().intValue());
        List<DynamicModel> list = dynamicMapper.select(dynamicModel);
        if (list == null) {
            return ResultModel.noData();
        }
        List<DynamicResponse> responseList = new ArrayList<>();
        list.forEach(cl -> {
            DynamicResponse dynamicResponse = new DynamicResponse();
            BeanUtils.copyProperties(cl, dynamicResponse);
            dynamicResponse.setDoThumbsName(doThumbsName(cl.getDoThumbsName()));
            responseList.add(dynamicResponse);
        });
        boolean fal = request.getMyCardId() == null || !request.getMyCardId().equals(request.getCardId());
        if (fal) {
            //添加查看记录
            addSeeRecord(request.getId().intValue(), request.getCardId(), null, SeeRecordEnums.ARTICLE.getCode(), request.getDynamicId());
        }
        PageInfo<DynamicResponse> pageInfo = new PageInfo<>(responseList);
        return ResultModel.success(pageInfo.getList());
    }



    @Override
    public ResultModel doDynamicThumbs(DynamicRequest request) {
        if (request.getId() == null || request.getDynamicId() == null) {
            return ResultModel.checkParamFail();
        }
        ThumbsModel model = new ThumbsModel();
        model.setItemId(request.getDynamicId());
        model.setUserId(request.getId().intValue());
        model.setItemType(2);
        Integer count = thumbsMapper.getIsThumbs(model);
        if (count == null || count <= 0) {
            String name = userMapper.selectNickeName(request.getId().toString().split(","));
            model.setUserName(name == null ? "" : new String(java.util.Base64.getDecoder().decode(name)));
            model.setCreateTime(currentDate());
            thumbsMapper.insertSelective(model);
            return ResultModel.success(model.getUserName());
        } else {
            thumbsMapper.delete(model);
        }
        boolean fal = request.getMyCardId() == null || !request.getMyCardId().equals(request.getCardId());
        if (fal) {
            //添加查看记录
            addSeeRecord(request.getId().intValue(), request.getCardId(), null, SeeRecordEnums.ARTICLE.getCode(), request.getDynamicId());
        }
        return ResultModel.success();
    }

    @Override
    public ResultModel selectComment(CommentRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        CommentModel model = new CommentModel();
        model.setDynamicId(request.getDynamicId());
        List<CommentModel> list = commentMapper.select(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        List<CommentResponse> responseList = new ArrayList<>();
        list.forEach(obj -> {
            {
                CommentResponse response = new CommentResponse();
                BeanUtils.copyProperties(obj, response);
                responseList.add(response);
            }
        });
        PageInfo<CommentResponse> pageInfo = new PageInfo<>(responseList);
        return ResultModel.success(pageInfo.getList());
    }

    @Autowired
    private WxMessageService wxMessageService;

    @Override
    public ResultModel doComment(CommentRequest request) {
        log.info("添加评论：{}", JSON.toJSONString(request));
        if (request == null || request.getDynamicId() == null || request.getId() == null) {
            return ResultModel.checkParamFail();
        }
        CommentModel model = new CommentModel();
        BeanUtils.copyProperties(request, model);
        model.setCreateTime(currentDate());
        model.setIsDel(0);
        model.setUserId(request.getId().intValue());
        commentMapper.insertSelective(model);
        Integer r = dynamicMapper.getCreateUserId(request.getDynamicId());
        if (r != null && r != request.getId().intValue()) {
            // 咨询回复通知微信推送提醒
            WxNoticeEntity entity = commentMapper.getSendTemplateInfo(model.getCommentId());
            String[] fillData = {entity.getNickeName(), getDay(), entity.getText()};
            wxMessageService.sendTemplate(entity.getCrmOpenId(), entity.getCrmFormId(), WxNoticeEnums.COMMENT_REPLY.getCode(), fillData,"&id="+entity.getDynamicId(), LoginEnum.CRM.getAccountType(),entity.getCrmCompanyId());
        }
        return ResultModel.success();
    }

    @Override
    public ResultModel delComment(CommentRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        CommentModel model = new CommentModel();
        model.setCommentId(request.getCommentId());
        model.setUserId(request.getId().intValue());
        List<CommentModel> list = commentMapper.select(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.fail("用户只能删除自己的评论！");
        }
        model.setIsDel(1);
        r = commentMapper.updateByPrimaryKeySelective(model);
        if (r > 0) {
            return ResultModel.success();
        }
        return ResultModel.fail();
    }


    @Override
    @Cacheable(value = RedisCode.REDIS_DB_CACHE,key = "#root.targetClass.toString()+'.'+#root.methodName+':'+#request.toString()")
    public ResultModel getWebsiteInfo(WebsiteRequest request) {
        if (request == null || request.getCompanyId() == null) {
            return ResultModel.checkParamFail();
        }
        WebsiteModel model = websiteMapper.select(new WebsiteModel(){{
            setCompanyId(request.getCompanyId());
        }});
        if (model == null) {
            return ResultModel.noData();
        }
        model.setRecruitModelList(companyRecruitMapper.select(new CompanyRecruitModel(){{
            setCompanyId(request.getCompanyId());
        }}));
        boolean fal = model.getWebsiteId() != null && (request.getMyCardId() == null || !request.getMyCardId().equals(request.getCardId()));
        if (fal) {
            //添加查看记录
            addSeeRecord(request.getId().intValue(), request.getCardId(), request.getCompanyId(), SeeRecordEnums.OFFICIAL_WEBSITE.getCode(), model.getWebsiteId());
        }
        WebsiteResponse websiteResponse = new WebsiteResponse();
        BeanUtils.copyProperties(model, websiteResponse);
        // 查询公司视频
        websiteResponse.setCompanyVideoModelList(companyVideoMapper.select(new CompanyVideoModel(){{setCompanyId(request.getCompanyId());}}));
        return ResultModel.success(websiteResponse);
    }

    @Override
    @Cacheable(value = RedisCode.REDIS_DB_CACHE,key = "#root.targetClass.toString()+'.'+#root.methodName+':'+#request.toString()+':'+#request.pageSize+':'+#request.pageNum")
    public ResultModel<List<CompanyRecruitResponse>> getCompanyRecruit(CompanyRecruitRequest request) {
                if (request == null) {
                    return ResultModel.checkParamFail();
        }
        CompanyRecruitModel websiteModel = new CompanyRecruitModel();
        BeanUtils.copyProperties(request, websiteModel);
        List<CompanyRecruitModel> list = companyRecruitMapper.select(websiteModel);
        if (list == null) {
            return ResultModel.noData();
        }
        List<CompanyRecruitResponse> responseList = new ArrayList<>();
        list.forEach(cl -> {
            CompanyRecruitResponse companyRecruitResponse = new CompanyRecruitResponse();
            BeanUtils.copyProperties(cl, companyRecruitResponse);
            responseList.add(companyRecruitResponse);
        });
        return ResultModel.success(responseList);
    }

    @Override
    public ResultModel addDemand(DemandRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        DemandModel model = new DemandModel();
        BeanUtils.copyProperties(request, model);
        model.setCreateTime(new Date());
        model.setIsDel(0);
        model.setLog(userMapper.selectByPrimaryKey(request.getId().intValue()).getAvatarUrl());
        model.setCardId(request.getCardId());
        r = demandMapper.insertSelective(model);
        if (r > 0) {
            // 咨询回复通知微信推送提醒
            WxNoticeEntity entity = demandMapper.getSendTemplateInfo(new DemandModel() {{
                setCardId(request.getCardId());
                setDemandId(model.getDemandId());
            }});
            String[] fillData = {entity.getName(), getDay(), entity.getText()};
            wxMessageService.sendTemplate(entity.getCrmOpenId(), entity.getCrmFormId(), WxNoticeEnums.FROM_SUBMIT.getCode(), fillData,LoginEnum.CRM.getAccountType(),entity.getCompanyId());
            return ResultModel.success("保存成功");
        }
        return ResultModel.fail("保存失败");
    }
}
